package com.example.demo.guava;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static java.lang.System.out;

/**
 * @description: xxx
 * @time: 2020/11/6 13:39
 * @author: baojinlong
 **/
public class CacheDemo {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            String accessToken = new AccessTokenProvider().getAccessToken();
            out.println(accessToken);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                out.println("错误");
            }

        }
    }


}


class AccessTokenProvider {
    private static final String KEY = "cache-key";
    static Cache<String, Optional<String>> cache = CacheBuilder.newBuilder()
            // 是3秒过期，这是为了测试。
            .expireAfterWrite(3, TimeUnit.SECONDS)
            // 监听过期。
            .removalListener((RemovalListener<String, Optional<String>>) removalNotification -> out.println("cache expired,remove " + removalNotification.getKey())).build();

    /**
     * 是先从 cache 中获取，如果没有获取到，从远程获取。
     *
     * @return
     */
    public String getAccessToken() {
        try {
            Optional<String> stringOptional = cache.get(KEY, () -> Optional.of(getRemoteAccessToken()));
            return stringOptional.orElse("");
        } catch (Exception exception) {
            return null;
        }
    }

    /**
     * 是模拟远程获取 token
     *
     * @return
     */
    private String getRemoteAccessToken() {
        return "accessToken:" + new Random().nextInt(1000);
    }
}